package org.example

import scala.io.Source
import scala.util.Try

object s2 {
  def main(args: Array[String]): Unit = {
    // 读取文件
    val filename = "src/main/resources/word.txt"
    val words = Try(Source.fromFile(filename).getLines().flatMap(_.split("\\W+")).toList).getOrElse(List.empty[String])

    if (words.isEmpty) {
      println("文件为空或无法读取！")
      return
    }

    // 1. 统计词频
    val wordFrequency = words.groupBy(identity).view.mapValues(_.size).toMap
    println("所有单词及其出现次数：")
    wordFrequency.foreach { case (word, count) => println(s"$word: $count") }

    // 2. 找出出现次数最多的前三个单词
    val topThreeWords = wordFrequency.toSeq.sortBy(-_._2).take(3)
    println("\n出现次数最多的前三个单词：")
    topThreeWords.foreach { case (word, count) => println(s"$word: $count") }

    // 3. 找出回文单词
    val palindromeWords = words.distinct.filter(word => word == word.reverse)
    println("\n回文单词：")
    palindromeWords.foreach(println)
  }
}
